import { onMounted, onBeforeUnmount } from "vue"
import {getDounceFunc} from "@/common/utils"

type configType = {
  containerSelector: string
  leftBoxSelector: string
  rightBoxSelector: string
  moveBarSelector: string
  lMinW?: number
  rMinW?: number
  innerMarginW?:number
  help?: boolean
}


/**
 * @description 布局由 容器、左侧元素、中间条元素、右侧元素组成。通过拖动中间的条元素，使得左右两部分元素的宽度变得可调整
 * @param config.containerSelector 容器元素的选择器
 * @param config.leftBoxSelector   左侧元素的选择器
 * @param config.rightBoxSelector  右侧元素的选择器
 * @param config.moveBarSelector   中间条元素的选择器
 * @param config.lMinW     左侧元素的最小宽度。默认0
 * @param config.rMinW       右侧元素的最小宽度。默认0
 * @param config.innerMarginW  容器布局内水平外边距占据的总宽度。默认0
 * @param config.help          是否需要在组件挂载时执行，卸载时取消事件绑定。默认true
 * @returns help为false时是取消绑定事件的函数。true时无返回值
 */
export function useResizeLR(config: configType) {
  const { help = true } = config
  if (help) {
    let remove: undefined | (()=>void)

    onMounted(() => {
      remove = apply(config)
    })

    onBeforeUnmount(() => {
      remove && remove()
    })
  } else return apply(config)

  function apply(config:configType) {
    const { containerSelector, leftBoxSelector, rightBoxSelector, moveBarSelector, lMinW = 0, rMinW = 0,innerMarginW=0 } = config
     
    type EL=HTMLElement | null
    const resizeC:EL = document.querySelector(containerSelector)
    const leftBox:EL = document.querySelector(leftBoxSelector)
    const moveBar:EL = document.querySelector(moveBarSelector)
    const rightBox:EL = document.querySelector(rightBoxSelector)

    moveBar!.style.cursor="col-resize"
    
    const initV = { lw: leftBox!.clientWidth,mW:moveBar!.offsetWidth,rw: rightBox!.clientWidth,cW:resizeC!.clientWidth}
    let mouseDowning = false
    const start = {
      x: 0,
      lw: 0,
      rw: 0,
    }
    
    const downHandler = (e:MouseEvent) => {
      //  console.log('down',e)
      if(resizeC!.clientWidth < lMinW+rMinW+initV.mW+innerMarginW) return
      mouseDowning = true
      start.lw = leftBox!.clientWidth
      start.rw = rightBox!.clientWidth
      start.x = e.x
    }
    const moveHandler = (e:MouseEvent) => {
      //  console.log('move',e)
      e.preventDefault()
      if (mouseDowning) {
        const x = e.x
        const w = Math.abs(x - start.x)
        let direction:'left' | 'right'
        let lbw:number, rbw:number
        if (x > start.x) {  
          lbw = start.lw + w
          rbw = start.rw - w
          direction='right'
        } else {
          lbw = start.lw - w
          rbw = start.rw + w
          direction='left'
        }
        const setWidth=()=>{
          leftBox!.style.width = lbw + 'px'
          rightBox!.style.width = rbw + 'px'
        }
        if(lbw>lMinW && rbw>rMinW) setWidth()
        // if(direction=='left'){
        //     if(lbw >= lMinW) {
        //       setWidth()
        //     }
        // }else{
        //    if(rbw >= rMinW){
        //      setWidth()
        //    }
        // }
      }
    }
    const endHandler = (e:MouseEvent) => {
      // console.log('end',e)
      mouseDowning = false
    }
    
    const containerResizeHandler=getDounceFunc(()=>{
       if(leftBox!.clientWidth != initV.lw){
        leftBox!.style.width=initV.lw+'px'
        rightBox!.style.width=`calc(100% - ${initV.lw + initV.mW + innerMarginW}px`;
       }
    },100,false)

    moveBar!.addEventListener('mousedown', downHandler)
    resizeC!.addEventListener('mousemove', moveHandler)
    resizeC!.addEventListener('mouseup', endHandler)
    resizeC!.addEventListener('mouseleave', endHandler)
   
    // 创建一个 ResizeObserver 实例
    const resizeObserver = new ResizeObserver(entries => {
      // 当dom尺寸变化时执行
      for (let entry of entries) {
        if(entry.target==resizeC){
          // console.log(entry.contentRect)
          containerResizeHandler()
        }
        // console.log('新的宽度：', entry.contentRect.width)
      }
    });

    // 将目标元素添加到 ResizeObserver 中进行监听
    resizeObserver.observe(resizeC!);

    return () => {
      moveBar!.style.cursor='unset'
      moveBar!.removeEventListener('mousedown', downHandler)
      resizeC!.removeEventListener('mousemove', moveHandler)
      resizeC!.removeEventListener('mouseup', endHandler)
      resizeC!.removeEventListener('mouseleave', endHandler)
      // resizeObserver.unobserve(resizeC!)  // 在ResizeObserver实例上取消指定dom的监听
      resizeObserver.disconnect()    // 在ResizeObserver实例上取消所有dom的监听
    }
  }

}



